﻿#ifndef AUTOFOCUS3_H
#define AUTOFOCUS3_H

#include <QtCore/QThread>
#include <QtCore/QList>
#include <QtCore/QVector>
#include <QtCore/QPoint>
#include <QtCore/QSemaphore>

#include "CameraCommon/CameraImage.h"
#include "StageControlB140/StageControl.h"
#include "AutoFocus/FocusMeasure.h"
#include "CameraImagingSource/TisCamera.h"

class AutoFocus3 : public QThread
{
    Q_OBJECT
public:
    AutoFocus3();
    void attach(CameraImage *image);
    void attach(StageControl *control);
    void attach(TisCamera * camera);
    void setRange(double lower_mm, double higher_mm, double speed); // 设置相对于当前位置的相对位移。
    double bestImage(QImage &image);
signals:
    void autoFocusFinished();
public slots:
    void startAutoFocus();
    void stop();
private slots:
    void setImage(const QImage &RGB24Image);
    void zMoveFinished();
    void watchdogTimeout();
private:
    void startWatchDog(int ms = 0);
    void stopWatchDog();
    CameraImage * m_pCameraImage = nullptr;
    StageControl *m_pStageControl = nullptr;
    TisCamera * m_pCamera = nullptr;
    FocusMeasure m_focusMeasure;
    QImage m_bestImage;
    bool m_isFocus = false;
    double m_bestScore = 0.0;
    double m_low_mm = 0.0;
    double m_high_mm = 0.0;
    double m_speed = 1.0;
    double m_z_mm = 0.0;
};

void AutoFocus3::attach(CameraImage *image)
{
    assert(image);
    m_pCameraImage = image;
    connect(m_pCameraImage, &CameraImage::imageChanged, this, &AutoFocus3::setImage);
}

void AutoFocus3::attach(StageControl *control)
{
    assert(control);
    m_pStageControl = control;
    connect(m_pStageControl, &StageControl::zMoveFinish, this, &AutoFocus3::zMoveFinished);
}

void AutoFocus3::attach(TisCamera *camera)
{
    assert(camera);
    m_pCamera = camera;
}

void AutoFocus3::setRange(double lower_mm, double higher_mm, double speed)
{
    m_low_mm = lower_mm;
    m_high_mm = higher_mm;
    m_speed = speed;
}

#endif // AUTOFOCUS3_H
